const ble = uni.requireNativePlugin('sand-plugin-bluetooth');

class YBKC_Sanhe_5101 {
	constructor() {
		this.currentDevice = null; // 当前连接的设备
		this.deviceCallbacks = {}; // 设备回调
		this.isScanning = false;
		this.initListener();
	}

	// 初始化监听
	initListener() {
		const that = this;

		// 设备发现监听
		ble.onBluetoothDeviceFound({}, (res) => {
			if (res.status == '2500') {
				let devices = JSON.parse(res.devices);
				if (typeof(that.callBackDeviceList) == "function") {
					that.callBackDeviceList(devices);
				}
			}
		});

		// 设备连接状态监听
		ble.onBLEConnectionStateChange({}, (res) => {
			const deviceId = res.deviceId;
			const connected = res.connected;

			console.log(`设备连接状态变化: ${deviceId} - ${connected}`);

			// 只处理当前设备的状态变化
			if (that.currentDevice && that.currentDevice.deviceId === deviceId) {
				that.currentDevice.connected = connected;

				if (connected) {
					console.log(`设备 ${deviceId} 连接成功，开始订阅特征`);
					that.notify(deviceId);
				} else {
					console.log(`设备 ${deviceId} 断开连接`);
					// 设备断开时重置当前设备
					that.currentDevice = null;
				}

				// 调用状态回调
				if (that.deviceCallbacks.onStatus) {
					that.deviceCallbacks.onStatus(deviceId, connected);
				}
			}
		});

		// 特征数据变化监听
		ble.onBLECharacteristicValueChange({}, (res) => {
			const deviceId = res.deviceId;

			// 只处理当前设备的数据
			if (that.currentDevice && that.currentDevice.deviceId === deviceId) {
				if (that.deviceCallbacks.onData) {
					const value = res.value;
					const originValue = that.hex2Bytes(value);

					if (originValue && originValue.length >= 7) {
						let Nums = (parseInt(parseInt(originValue[5]) * 256) + parseInt(originValue[6])) /
							100;
						if (!isNaN(Nums)) {
							let AllNums = (parseInt(parseInt(originValue[4]) * 65536) +
								parseInt(parseInt(originValue[5]) * 256) +
								parseInt(originValue[6]));
							Nums = AllNums / 100;

							const dataObj = {
								deviceId: deviceId,
								Nums: Nums,
								Model: res,
								timestamp: new Date().getTime()
							};

							console.log(`设备数据: ${dataObj.Nums}`);
							that.deviceCallbacks.onData(dataObj);
						}
					}
				}
			}
		});

		// 打开蓝牙适配器
		ble.openBluetoothAdapter({}, (res) => {
			console.log('蓝牙适配器状态:', res);
		});
	}

	// 连接设备
	Link(deviceConfig, callBackDeviceList, callBackLinkSuccess) {
		if (!deviceConfig || !deviceConfig.deviceId) {
			// 扫描模式
			this.callBackDeviceList = callBackDeviceList;
			this.startScan();
		} else {
			// 连接指定设备
			this.toConnect(deviceConfig, callBackLinkSuccess);
		}
	}

	// 开始扫描
	startScan() {
		if (this.isScanning) return;

		this.isScanning = true;
		ble.startBluetoothDevicesDiscovery({}, (res) => {
			console.log('开始扫描设备:', res);
		});
	}

	// 停止扫描
	StopFind() {
		this.isScanning = false;
		ble.stopBluetoothDevicesDiscovery({}, (res) => {
			console.log('停止扫描设备:', res);
		});
	}

	// 连接设备
	toConnect(deviceConfig, callBackLinkSuccess) {
		const deviceId = deviceConfig.deviceId;

		// 停止扫描
		this.StopFind();

		// 设置当前设备
		this.currentDevice = {
			deviceId: deviceId,
			config: deviceConfig,
			connected: false
		};

		console.log(`开始连接设备: ${deviceId}`);

		// 开始连接
		ble.createBLEConnection({
			deviceId: deviceId
		}, (res) => {
			console.log(`设备连接结果:`, res);

			if (typeof(callBackLinkSuccess) == "function") {
				callBackLinkSuccess(res);
			}

			if (res.status === '2500') {
				this.currentDevice.connected = true;
			}
		});
	}

	// 断开设备连接
	Disconnect(deviceId) {
		if (this.currentDevice && this.currentDevice.deviceId === deviceId) {
			console.log(`断开设备连接: ${deviceId}`);
			ble.closeBLEConnection({
				deviceId: deviceId
			}, (res) => {
				this.currentDevice = null;
				console.log(`设备 ${deviceId} 已断开`);
			});
		}
	}

	// 获取已连接设备
	getConnected(callBackGetLink) {
		ble.getConnectedBluetoothDevices({}, (res) => {
			let devices = JSON.parse(res.devices) || [];
			if (typeof(callBackGetLink) == "function") {
				callBackGetLink(res);
			}
		});
	}

	// 设置设备数据回调
	CallBackGetData(deviceId, callBackData) {
		console.log(`设置数据回调`);
		this.deviceCallbacks.onData = callBackData;
	}

	// 设置设备状态回调
	GetStatus(deviceId, callBackGetStatus) {
		console.log(`设置状态回调`);
		this.deviceCallbacks.onStatus = callBackGetStatus;
	}

	// 写入数据
	WriteData(deviceId, data) {
		console.log(`写入数据:`, data);
	}

	// 订阅特征通知
	notify(deviceId) {
		console.log(`开始订阅设备特征`);
		console.log(deviceId);
		setTimeout(() => {
			ble.getBLEDeviceServices({
				deviceId: deviceId
			}, (res) => {
				console.log(res);
				if (res.status == '2500') {
					let services = JSON.parse(res.services);
					console.log(services);
					console.log(`发现服务:`, services.length);
					this.subscribeToCharacteristics(deviceId, services, 0);
				} else {
					console.log(`获取服务失败:`, res);
				}
			});
		}, 500);
	}

	// 递归订阅特征
	subscribeToCharacteristics(deviceId, services, index) {
		if (index >= services.length) return;
		console.log(deviceId);
		console.log(services[index].uuid);
		ble.getBLEDeviceCharacteristics({
			deviceId: deviceId,
			serviceId: services[index].uuid
		}, (res) => {
			console.log(res);
			if (res.status !== '2500') {
				console.log(`获取特征失败:`, res);
				this.subscribeToCharacteristics(deviceId, services, index + 1);
				return;
			}

			let characteristics = JSON.parse(res.characteristics);
			console.log(`发现特征:`, characteristics.length);

			for (let characteristic of characteristics) {
				if (characteristic.properties.notify) {
					console.log(services);
					console.log(deviceId);
					console.log(services[index].uuid);
					console.log(characteristic.uuid);

					ble.notifyBLECharacteristicValueChange({
						deviceId: deviceId,
						serviceId: services[index].uuid,
						characteristicId: characteristic.uuid
					}, (res3) => {
						if (res3.status === '2500') {
							console.log(`订阅特征成功`);
						} else {
							console.log(`订阅特征失败:`, res3);
						}
					});
				}
			}

			// 递归下一个服务
			this.subscribeToCharacteristics(deviceId, services, index + 1);
		});
	}

	// 十六进制转字节数组
	hex2Bytes(hexStr) {
		let pos = 0;
		let len = hexStr.length;
		if (len % 2 != 0) return null;

		len /= 2;
		let hexA = [];
		for (let i = 0; i < len; i++) {
			let s = hexStr.substr(pos, 2);
			let v = parseInt(s, 16);
			hexA.push(v);
			pos += 2;
		}
		return hexA;
	}

	// 获取当前设备ID
	getCurrentDeviceId() {
		return this.currentDevice ? this.currentDevice.deviceId : null;
	}

	// 获取设备连接状态
	isDeviceConnected() {
		return this.currentDevice ? this.currentDevice.connected : false;
	}
}

export default YBKC_Sanhe_5101;